package com.brush.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brush.common.constant.CacheConstants;
import com.brush.common.exception.ServiceException;
import com.brush.common.exception.database.PrimaryKeyException;
import com.brush.common.exception.database.RecordNotFoundException;
import com.brush.common.utils.MessageUtils;
import com.brush.system.domain.SysConfig;
import com.brush.system.domain.req.sysconfig.SysConfigAddReq;
import com.brush.system.domain.req.sysconfig.SysConfigEditReq;
import com.brush.system.domain.req.sysconfig.SysConfigQueryReq;
import com.brush.system.domain.resp.sysconfig.SysConfigResp;
import com.brush.system.mapper.SysConfigMapper;
import com.brush.system.service.SysConfigService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author 18494
 * @description 针对表【sys_config(参数配置表)】的数据库操作Service实现
 * @createDate 2024-08-19 10:28:03
 */
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig>
        implements SysConfigService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据key获取配置值
     *
     * @return
     */
    @Override
    public String getConfigValueByKey(String configKey) {


        // 做redis缓存的查询
        if (redisTemplate.hasKey(CacheConstants.SYS_CONFIG_KEY + configKey)) {
            return (String) redisTemplate.opsForValue().get(CacheConstants.SYS_CONFIG_KEY + configKey);
        }

        // 创建一个查询对象 select * from sys_config
        // 第29行相当于 where config_key = 'sys.login.blackIPList'
        LambdaQueryWrapper<SysConfig> queryWrapper = new LambdaQueryWrapper<>();
        // eq == , ge >= , le <= , gt > , lt < , https://baomidou.com/guides/wrapper/#ge
        queryWrapper.eq(SysConfig::getConfigKey, configKey);
        // 执行查询，获取结果
        SysConfig sysConfig = this.getOne(queryWrapper);
        // 查询不到
        if (Objects.isNull(sysConfig)) {
            return StrUtil.EMPTY;
        }

        // 数据库中配置了黑名单
        if (StrUtil.isNotBlank(sysConfig.getConfigValue())) {
            // 将黑名单数据存入redis
            redisTemplate.opsForValue().set(CacheConstants.SYS_CONFIG_KEY + sysConfig.getConfigKey(), sysConfig.getConfigValue());
            return sysConfig.getConfigValue();
        }

        // 存入redis中（值为“”）
        redisTemplate.opsForValue().set(CacheConstants.SYS_CONFIG_KEY + sysConfig.getConfigKey(), StrUtil.EMPTY);
        return StrUtil.EMPTY;
    }

    @Override
    public PageInfo<SysConfigResp> paginationQuery(SysConfigQueryReq req) {

        return PageHelper.startPage(req.getPageNum(), req.getPageSize()).doSelectPageInfo(() -> {
            // 调用sysConfigMapper[mybatis]的分页查询方法, 要么使用lambdaQueryWrapper来写【mybatis-plus】
            // 一定返回的结果是 List<SysConfigResp>
            this.baseMapper.paginationQuery(req);
        });
    }

    /**
     * 新增参数配置
     *
     * @param req
     * @return
     */
    @Override
    public boolean add(SysConfigAddReq req) {
        // 验证configKey是否已经存在
        if (this.baseMapper.exists(new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getConfigKey, req.getConfigKey()))) {
            throw new ServiceException(MessageUtils.message("sysconfig.configKey.exists"));
        }

        SysConfig newEntity = new SysConfig();

        BeanUtils.copyProperties(req, newEntity);

        boolean save = this.save(newEntity);
        if (save) {
            // 清空缓存
            redisTemplate.opsForValue().set(CacheConstants.SYS_CONFIG_KEY + req.getConfigKey(), newEntity);
        }

        return save;
    }


    @Override
    public SysConfigResp findById(Long id) {
        if (Objects.isNull(id)) {
            throw new PrimaryKeyException();
        }

        // 根据主键查询
        SysConfig db = this.getById(id);
        // 数据库找不到数据
        if (Objects.isNull(db)) {
            throw new RecordNotFoundException();
        }

        // 封装成返回对象
        SysConfigResp resp = new SysConfigResp();
        BeanUtils.copyProperties(db, resp);

        return resp;
    }

    /**
     * 修改参数配置
     *
     * @param req
     * @return
     */
    @Override
    public boolean edit(SysConfigEditReq req) {
        // 根据主键查询
        SysConfig db = this.getById(req.getConfigId());
        // 数据库找不到数据
        if (Objects.isNull(db)) {
            throw new RecordNotFoundException();
        }

        // 验证configKey是否已经存在
        if (!req.getConfigKey().equals(db.getConfigKey())) {
            // 判断configKey是否已经被使用
            if (this.baseMapper.exists(new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getConfigKey, req.getConfigKey()))) {
                throw new ServiceException(MessageUtils.message("sysconfig.configKey.exists"));
            }
        }

        // 覆盖数据库对象的值
        BeanUtils.copyProperties(req, db);
        boolean result = this.updateById(db);
        if (result) {
            // 覆盖缓存
            redisTemplate.opsForValue().set(CacheConstants.SYS_CONFIG_KEY + db.getConfigKey(), db);
        }
        return result;
    }

    /**
     * 删除sysconfig指定的id并删除缓存
     *
     * @param ids
     * @return
     * @Transactional 循环向数据库操作，必须使用事务特效
     */
    @Transactional(rollbackFor = Exception.class)  // 添加数据库事务
    @Override
    public boolean deleteById(Long[] ids) {
        if (Objects.isNull(ids) || ids.length == 0) {
            throw new PrimaryKeyException();
        }

        final SysConfigServiceImpl sysConfigService = this;

        this.redisTemplate.execute(new SessionCallback<Void>() {
            @Override
            public Void execute(RedisOperations operations) throws DataAccessException {
                // 开启redis事务
                operations.multi();

                // 循环删除数据库数据，时间复杂度：O(n)，事务问题
                try {
                    for (Long id : ids) {
                        SysConfig db = sysConfigService.getById(id);
                        // 数据库找到数据
                        if (Objects.nonNull(db)) {
                            // 删除数据库中的值
                            sysConfigService.removeById(id);
                            // 移除缓存中的值
                            String redisKey = CacheConstants.SYS_CONFIG_KEY + db.getConfigKey();
                            operations.delete(redisKey);
                        }
                    }

                    // 提交redis事务
                    operations.exec();
                } catch (Exception e) {
                    // 回滚redis事务
                    operations.discard();
                    throw e;
                }
                return null;
            }
        });


        return true;
    }

    @Override
    public List<SysConfigResp> export(SysConfigQueryReq req, Long[] ids) {
        List<SysConfigResp> dataList = new ArrayList<>();
        // 根据主键导出
        if (Objects.nonNull(ids) && ids.length > 0) {
            dataList = this.baseMapper.exportByIds(ids);
        } else {
            //按条件查询
            dataList = this.baseMapper.paginationQuery(req);
        }


        return dataList;
    }
}




